<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="4">
                <el-tag
                  closable
                  @close="deleteRightById(item1.id, scope.row)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="20">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="deleteRightById(item2.id, scope.row)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="deleteRightById(item3.id, scope.row)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEditRolesDialog(scope.row.id)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesVisible"
      width="50%"
      @close="closeAddRoleDialog"
    >
      <el-form
        :model="addRolesForm"
        :rules="addRolesRules"
        ref="addRolesRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesVisible"
      width="50%"
      @close="closeEditRoleDialog"
    >
      <el-form
        :model="editRolesForm"
        :rules="editRolesRules"
        ref="editRolesRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsVisible"
      width="50%"
      @close="closeSetRightsDialog"
    >
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    // 获取角色列表
    this.getRoleList();
  },
  data() {
    return {
      // 角色列表
      roleList: [],
      // 用于显示或隐藏添加用户对话框
      addRolesVisible: false,
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      addRolesRules: {
        roleName: [
          { required: true, message: "角色名称不可为空！", trigger: "blur" },
        ],
      },
      // 用于显示或隐藏修改用户对话框
      editRolesVisible: false,
      editRolesForm: {
        roleId: 1,
        roleName: "",
        roleDesc: "",
      },
      editRolesRules: {
        roleName: [
          { required: true, message: "角色名称不可为空！", trigger: "blur" },
        ],
      },
      // 用于显示或隐藏修改分配权限对话框
      setRightsVisible: false,
      // 用于存储所有权限
      rightsList: [],
      // 属性控件的属性绑定
      rightsProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中的节点id值数组
      defaultKeys: [],
      // 表示此时需要分配权限的角色id
      roleId: "",
    };
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("查询角色列表失败！");
      }
      this.roleList = res.data;
    },
    // 单击确定按钮，添加角色
    addRoles() {
      // 首先进行预验证
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 发送ajax请求
        const { data: res } = await this.$http.post("roles", this.addRolesForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败！");
        }
        this.$message.success("添加角色成功！");
        this.addRolesVisible = false;
        // 添加成功后，再次显示角色列表
        this.getRoleList();
      });
    },
    // 添加角色对话框关闭时调用的函数，用于清空表单验证
    closeAddRoleDialog() {
      this.$refs.addRolesRef.resetFields();
    },
    // 显示修改角色对话框
    async showEditRolesDialog(id) {
      // 根据id查询角色
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色信息失败！");
      }
      this.editRolesForm = res.data;
      this.editRolesVisible = true;
    },
    // 修改角色对话框关闭时调用的函数，用于清空表单验证
    closeEditRoleDialog() {
      this.$refs.editRolesRef.resetFields();
    },
    // 单击确定按钮，修改角色
    editRoles() {
      // 首先进行预验证
      this.$refs.editRolesRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 发送ajax请求
        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesForm.roleId,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改角色失败！");
        }
        this.$message.success("修改角色成功！");
        this.editRolesVisible = false;
        this.getRoleList();
      });
    },
    // 根据id删除角色
    async deleteRolesById(id) {
      // 使用 element-ui 的确认消息组件
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 删除成功后，重新显示角色列表
          this.getRoleList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 根据roleId和rightId删除权限
    async deleteRightById(rightId, role) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发送ajax请求
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );

          if (res.meta.status !== 200) {
            return this.$message.error("删除失败！");
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });

          role.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 显示分配权限对话框
    async showSetRightsDialog(role) {
      // 打开分配权限对话框后，将此时需要被分配权限的角色id赋值
      this.roleId = role.id;

      // 以树形结构获取所有权限
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rightsList = res.data;

      this.getRights(role, this.defaultKeys);

      this.setRightsVisible = true;
    },

    // 递归获取角色初始化三级权限列表
    getRights(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getRights(item, arr);
      });
    },

    // 关闭分配权限对话框时要处理的事件
    closeSetRightsDialog() {
      this.defaultKeys = [];
    },

    // 单击确定按钮，分配权限
    async setRights() {
      // 得到需要分配的权限id
      const arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // 将id数组转为字符串
      const ids = arr.join(",");
      // 发送ajax请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: ids,
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }

      this.$message.success(res.meta.msg);

      this.setRightsVisible = false;

      this.getRoleList();
    },
  },
};
</script>

<style>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>